package com.kanshu.ksgb.fastread.doudou.common.imageloader;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.GenericTransitionOptions;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.common.util.ThreadPoolUtil;

import static com.bumptech.glide.Glide.with;

/**
 * Created by wcy on 2017/4/14.
 */

public class GlideImageLoader {

    private GlideImageLoader() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    //默认配置
    private static GlideImageConfig sDefConfig = new GlideImageConfig.Builder().
            setCropType(GlideImageConfig.CENTER_CROP).
            setAsBitmap(true).
            setPlaceHolderResId(R.mipmap.ic_default_pic).
            setErrorResId(R.mipmap.ic_default_pic).
            setAnimResId(R.anim.fade_out).
            setDiskCacheStrategy(GlideImageConfig.DiskCache.ALL).
            setPriority(GlideImageConfig.LoadPriority.NORMAL).build();
    private static GlideImageConfig sEmptyConfig;


    public static void load(Context context, ImageView imageView, Object objUrl, GlideImageConfig config, final GlideLoadingListener listener, final  GlideBitmapLoadingListener callback)  {
        if (null == objUrl) {
            return;
        } else if (null == config) {
            config = sDefConfig;
        }
        try {
            RequestBuilder builder = with(context).load(objUrl);
            RequestOptions options = new RequestOptions();
            if (config.getCropType() == GlideImageConfig.CENTER_CROP) {
                options.centerCrop();
            } else {
                options.fitCenter();
            }

            int round = config.getRoundedRadius();
            if(round > 0){
                options.transform(new RoundedCorners(config.getRoundedRadius())) ;
            }
            //缓存设置
            options.diskCacheStrategy(config.getDiskCacheStrategy().getStrategy()).
                    skipMemoryCache(config.isSkipMemoryCache()).
                    priority(config.getPriority().getPriority());
            options.dontAnimate();

            if (null != config.getTag()) {
                options.signature(new GlideUrl(config.getTag()));
            } else {
                options.signature(new GlideUrl(objUrl.toString()));
            }

/*            if (null != config.getAnimator()) {
                builder.animate(config.getAnimator());
            } else if (null != config.getAnimResId()) {
                builder.animate(config.getAnimResId());
            }*/
            GenericTransitionOptions transitionOptions = GenericTransitionOptions.with(R.anim.fade_out);
            builder.transition(transitionOptions);
            if (config.getPlaceHolderResId() != null) {
                options.placeholder(config.getPlaceHolderResId());
            }
            if (config.getErrorResId() != null) {
                options.error(config.getErrorResId());
            }
            if (null != config.getThumbnailUrl()) {
                RequestBuilder thumbnailRequest = with(context).load(config.getThumbnailUrl());
                builder.thumbnail(thumbnailRequest).into(imageView);
            } else {
                setTargetView(builder, config, imageView, callback);
            }
            builder.apply(options).into(imageView);
        } catch (Exception e) {
            try {
                imageView.setImageResource(config.getErrorResId());
            } catch (Exception e1) {
            }
            if (callback != null) {
                callback.onError();
            }
        }
    }


    public static void load(Context context, ImageView imageView, Object objUrl, GlideImageConfig config, final GlideLoadingListener listener) {
        load(context, imageView, objUrl, config, listener, null);
    }

    private static void setListener(RequestBuilder request, final GlideLoadingListener listener) {
        request.listener(new RequestListener() {
            @Override
            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target target, boolean isFirstResource) {
                listener.onError();
                return false;
            }

            @Override
            public boolean onResourceReady(Object resource, Object model, Target target, DataSource dataSource, boolean isFirstResource) {
                listener.onSuccess();
                return false;
            }

        });
    }

    private static void setTargetView(RequestBuilder request, GlideImageConfig config, ImageView view, final GlideBitmapLoadingListener listener) {
        //set targetView
        if (null != config.getSimpleTarget()) {
            request.into(config.getSimpleTarget());
        } else if (null != config.getViewTarget()) {
            request.into(config.getViewTarget());
        } else if (null != config.getNotificationTarget()) {
            request.into(config.getNotificationTarget());
        } else if (null != config.getAppWidgetTarget()) {
            request.into(config.getAppWidgetTarget());
        } else {
            if (listener != null) {
                try {
                    request.into(new SimpleTarget<BitmapDrawable>() {
                        @Override
                        public void onResourceReady(@NonNull BitmapDrawable resource, @Nullable Transition<? super BitmapDrawable> transition) {
                            if (listener != null) {
                                listener.onSuccess(resource.getBitmap());
                            }
                        }
                    });
                } catch (ClassCastException e) {
                    e.printStackTrace();
                }
            } else {
                request.into(view);
            }
        }
    }


    public static void load(Object url, ImageView imageView) {
        load(imageView.getContext(), imageView, url, sDefConfig, null, null);
    }

    public static void load(Object url, ImageView imageView, GlideImageConfig config) {
        load(imageView.getContext(), imageView, url, config, null, null);
    }

    public static void load(Object url, ImageView imageView, GlideImageConfig config, GlideBitmapLoadingListener listener) {
        load(imageView.getContext(), imageView, url, config, null, listener);
    }

    public static void load(Object url, ImageView imageView, GlideBitmapLoadingListener listener) {
        load(imageView.getContext(), imageView, url, sDefConfig, null, listener);
    }

    /**
     * 先加载gif，如果加载不成功，以普通图片加载
     * @param url
     * @param imageView
     * @param listener
     */
    @SuppressLint("CheckResult")
    public static void loadGif(Object url, ImageView imageView, GlideBitmapLoadingListener listener) {
        if (url == null) {
            if (listener != null) {
                listener.onError();
            }
            return;
        }
        RequestOptions options = new RequestOptions();
        options.centerCrop();
        RequestBuilder<GifDrawable> builder = with(Xutils.getContext()).asGif().load(url);
        builder.apply(options);
        builder.into(new SimpleTarget<GifDrawable>() {
            @Override
            public void onResourceReady(@NonNull GifDrawable resource, @Nullable Transition<? super GifDrawable> transition) {
                Log.d("wct", "");
                if (listener != null) {
                    listener.onSuccess(null);
                }
            }

            @Override
            public void onLoadFailed(@Nullable Drawable errorDrawable) {
                super.onLoadFailed(errorDrawable);
                load(url, imageView,sEmptyConfig, new GlideBitmapLoadingListener() {
                    @Override
                    public void onSuccess(Bitmap bitmap) {
                        if (listener != null) {
                            listener.onSuccess(bitmap);
                        }
                    }

                    @Override
                    public void onError() {
                        if (listener != null) {
                            listener.onError();
                        }
                    }
                });
            }
        });
        builder.into(imageView);
    }

    public static void load(Object objUrl, ImageView imageView, final GlideLoadingListener listener) {
        load(imageView.getContext(), imageView, objUrl, sDefConfig, listener, null);
    }


    /**
     * 暂停所有正在下载或等待下载的任务
     *
     * @param context Context
     */
    public static void pauseAllTasks(Context context) {
        with(context).pauseRequests();
    }

    /**
     * 恢复所有任务
     *
     * @param context Context
     */
    public static void resumeAllTasks(Context context) {
        with(context).resumeRequests();
    }

    /**
     * 清除磁盘缓存
     *
     * @param context Context
     */
    public static void clearDiskCache(final Context context) {
        ThreadPoolUtil.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                Glide.get(context).clearDiskCache();
            }
        });
    }

    public static void trimMemory(Context context, int level) {
        try {
            Glide.get(context).trimMemory(level);
        } catch (Exception e) {
        }
    }

    public static void clearMemory(Context context) {
        Glide.get(context).clearMemory();
    }


    /**
     * 清除所有缓存
     *
     * @param context Context
     */
    public static void cleanAll(Context context) {
        clearDiskCache(context);
        Glide.get(context).clearMemory();
    }

    /**
     * 清除目标View
     *
     * @param view the target view
     */
    public static void clearTarget(View view) {
       Glide.with(view).clear(view);
    }


    public static GlideImageConfig getEmptyConfig() {
        if (sEmptyConfig != null) {
            return sEmptyConfig;
        }
        sEmptyConfig = new GlideImageConfig.Builder().
                setCropType(GlideImageConfig.CENTER_CROP).
                setAsBitmap(true).
                setPlaceHolderResId(R.drawable.empty_bg).
                setErrorResId(R.drawable.empty_bg).
                setAnimResId(R.anim.fade_out).
                setDiskCacheStrategy(GlideImageConfig.DiskCache.SOURCE).
                setPriority(GlideImageConfig.LoadPriority.NORMAL).build();
        return sEmptyConfig;
    }
}
